package org.suren.littlebird.actions.logger;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.suren.littlebird.Activator;
import org.suren.littlebird.actions.Reload;
import org.suren.littlebird.preferences.PreferenceConstants;

/**
 * @author suren
 * @date 2015-4-1
 *
 * http://surenpi.com
 */
public class AbstractSuRenLoggerBridgeAction extends Action
{
	private static final IPreferenceStore store = Activator.getDefault().getPreferenceStore();
	private String bridgeIp;
	private int bridgePort;

	public void control(Table table, final SuRenLoggerController controller, final Reload reload, final int action)
	{
		TableItem[] selectionItems = table.getSelection();
		if(selectionItems == null || selectionItems.length == 0)
		{
			return;
		}

		bridgeIp = store.getString(PreferenceConstants.P_LOGGER_BRIDGE_IP);
		bridgePort = store.getInt(PreferenceConstants.P_LOGGER_BRIDGE_PORT);
		if(bridgeIp == null || "".equals(bridgeIp))
		{
			bridgeIp = getBridgeAddress();
		}

		System.out.println(bridgeIp);

		final String[] names = new String[selectionItems.length];
		for(int i = 0; i < selectionItems.length; i++)
		{
			names[i] = selectionItems[i].getText(1);
		}

		new Job("Logger Bridge Control"){

			@Override
			protected IStatus run(IProgressMonitor pro)
			{
				for(String name : names)
				{
					pro.setTaskName(name);

					controller.bridge(action, name, bridgeIp, bridgePort);

					Display.getDefault().syncExec(new Runnable()
					{

						@Override
						public void run()
						{

							if(reload != null)
							{
								reload.reload(null, null);
							}
						}
					});
				}

				return Status.OK_STATUS;
			}
		}.schedule();
	}

	private String getBridgeAddress()
	{
		String osgiServer = store.getString(PreferenceConstants.P_OSGI_SERVER);

		try
		{
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while(interfaces.hasMoreElements())
			{
				NetworkInterface network = interfaces.nextElement();
				if(network.isUp() && !network.isLoopback() && !network.isVirtual())
				{
					if(InetAddress.getByName(osgiServer).isReachable(network, 0, 2000))
					{
						Enumeration<InetAddress> inetAddrs = network.getInetAddresses();
						while(inetAddrs.hasMoreElements())
						{
							InetAddress addr = inetAddrs.nextElement();
							if(addr instanceof Inet4Address)
							{
								String hostAddr = addr.getHostAddress();
								store.setDefault(PreferenceConstants.P_LOGGER_BRIDGE_IP, hostAddr);

								return hostAddr;
							}
						}
					}
				}
			}
		}
		catch (SocketException e)
		{
			e.printStackTrace();
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		return null;
	}
}
